<template>
  <el-card class="w-full pt-[5px]">
    <CheckType
      v-model="searchForm.checkstatusByGroup"
      @typeChange="handleSearch"
      :countMap="countMap"
    />
    <el-form :model="searchForm" class="mt-[20px]" label-width="96px" ref="searchFormRef">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="项目负责人" class="mb-[0px]" prop="chargerName">
            <el-input v-model="searchForm.chargerName" placeholder="项目负责人" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目名称" class="mb-[0px]" prop="name">
            <el-input v-model="searchForm.name" placeholder="项目名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请人" class="mb-[0px]" prop="applyer">
            <el-input v-model="searchForm.applyer" placeholder="申请人" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <div class="flex justify-end">
            <el-button type="primary" @click="searchFormOpen = !searchFormOpen"
              >更多
              <el-icon color="#fff">
                <CaretTop v-show="searchFormOpen" />
                <CaretBottom v-show="!searchFormOpen" />
              </el-icon>
            </el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="mt-[20px]" v-show="searchFormOpen">
        <el-col :span="12">
          <el-form-item label="" label-width="0">
            <div class="w-full flex items-center">
              <el-date-picker
                v-model="searchForm.startTime"
                type="date"
                clearable
                placeholder="申请时间"
                value-format="YYYY-MM-DD"
                :disabled-date="
                  (date) =>
                    new Date(formatDate(date, 'YYYY-MM-DD')).getTime() >
                    new Date(searchForm.endTime || '').getTime()
                "
              />
              <span style="width: 20px; text-align: center; font-size: 14px"> 至 </span>
              <el-date-picker
                v-model="searchForm.endTime"
                type="date"
                clearable
                placeholder="申请时间"
                value-format="YYYY-MM-DD"
                :disabled-date="
                  (date) =>
                    new Date(formatDate(date, 'YYYY-MM-DD')).getTime() <
                    new Date(searchForm.startTime || '').getTime()
                "
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <el-card class="w-full pt-[5px] mt-[10px]">
    <div class="mb-[20px]">
      <template v-if="verifyRoleType.isKyryOrkycgly()">
        <el-button type="primary" @click="handleAdd">
          <el-icon class="mr-[5px]"><Plus /></el-icon>
          新增
        </el-button>
        <el-button @click="handleDelSelect">
          <el-icon class="mr-[5px]"><DeleteFilled /></el-icon>
          删除
        </el-button>
      </template>
      <template v-if="verifyRoleType.iskycgly()">
        <el-button @click="handleExport">
          <svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出
        </el-button>
      </template>
    </div>
    <el-table
      :data="tableData"
      class="w-full"
      stripe
      row-key="id"
      v-loading="loading"
      ref="tableRef"
    >
      <el-table-column
        type="selection"
        width="40"
        :selectable="
          (row) =>
            row.checkstatus == -1 ||
            row.checkstatus == 3 ||
            (verifyRoleType.iskycgly() && row.checkstatus == 2)
        "
      />
      <el-table-column prop="name" label="项目名称">
        <template #default="{ row }">
          <el-link type="primary" @click="handleView(row.id)">{{ row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="chargerName" label="项目负责人" width="100"> </el-table-column>
      <el-table-column label="所属单位" width="120">
        <template #default="{ row }">
          <CommonTreeLabel
            :dataList="unitList"
            valueKey="codeColumn"
            labelKey="valueColumn"
            :value="row.unitId"
          />
        </template>
      </el-table-column>
      <el-table-column prop="applyer" label="申请人" width="100"> </el-table-column>
      <el-table-column prop="applyTime" label="申请时间" width="100"> </el-table-column>
      <el-table-column label="审核状态" width="100">
        <template #default="{ row }">
          <CommonLabel
            :dataList="checkStatusList"
            valueKey="dictValue"
            labelKey="dictLabel"
            :value="row.checkstatus"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="140" align="center">
        <template #default="{ row }">
          <!-- 科研人员 -->
          <template v-if="verifyRoleType.isKyry()">
            <template v-if="[-1, 3].includes(Number(row.checkstatus))">
              <el-button
                type="primary"
                size="small"
                plain
                @click="handleEdit(row.id, row.isAuditor, row.taskId)"
              >
                编辑
              </el-button>
              <el-button type="danger" size="small" plain @click="handleDel(row.id)"
                >删除</el-button
              >
            </template>
            <el-button
              type="warning"
              size="small"
              plain
              @click="handleCancel(row.processInstanceId, row.id)"
              v-if="row.checkstatus == 1 && userId == row.chargerCode"
              :loading="cancelLoading && cancelId == row.id"
              >撤销</el-button
            >
          </template>
          <!-- 科研管理员 -->
          <template v-if="verifyRoleType.iskycgly()">
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleEdit(row.id, row.isAuditor, row.taskId)"
              v-if="[-1, 1, 2, 3].includes(Number(row.checkstatus))"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              size="small"
              plain
              @click="handleCheck(row.id, row.processInstanceId)"
              v-if="row.isAuditor"
              >审核</el-button
            >
            <el-button
              type="danger"
              size="small"
              plain
              @click="handleDel(row.id)"
              v-if="[-1, 2, 3].includes(Number(row.checkstatus))"
              >删除</el-button
            >
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-[20px] flex justify-end">
      <el-pagination
        v-bind="pagination"
        @update:current-page="currentChange"
        @update:page-size="sizeChange"
      />
    </div>
  </el-card>
  <EditModal ref="editModalRef" @save-success="handleSearch" />
  <CheckModal ref="checkModalRef" @check-success="handleSearch" />
  <ViewModal ref="viewModalRef" />
  <exportModal
    v-model="exportVisible"
    :selectList="exportFieldList"
    :title="exportTitle"
    @callBack="handleSelectOk"
  />
</template>

<script setup>
import { getList, delRecords, exportRecords, getCount } from "@/api/llsc";
import useTable from "@/hooks/useTable";
import { cancelProcess, exportFields } from "@/api/project/common";
import CheckType from "@/views/project/components/CheckType.vue";
import CommonTreeLabel from "@/views/project/components/CommonTreeLabel.vue";
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import EditModal from "./components/EditModal.vue";
import CheckModal from "./components/CheckModal.vue";
import ViewModal from "./components/ViewModal.vue";
import exportModal from "@/components/export";
import useCommonFetch from "@/hooks/useCommonFetch";
import useDictFetch from "@/hooks/useDictFetch";
import { verifyRoleType, downloadFile } from "@/utils/main";
import { formatDate } from "@/utils/formatTime";
import { ElMessageBox, ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const userId = userStore.userRealId;
const unitList = useCommonFetch("成果归属单位");
const checkStatusList = useDictFetch("bpm_process_instance_status"); //审核状态
const searchForm = ref({
  checkstatusByGroup: "",
  chargerName: "",
  name: "",
  applyer: "",
  startTime: "",
  endTime: "",
});
const searchFormRef = ref();
const searchFormOpen = ref(false);
const tableRef = ref();
const editModalRef = ref();
const checkModalRef = ref();
const viewModalRef = ref();
const exportFieldList = ref([]);
const exportVisible = ref(false);
const exportTitle = "伦理审查";
const cancelLoading = ref(false);
const cancelId = ref(null);
const countMap = ref({
  total: 0,
  1: 0,
  2: 0,
  3: 0,
});
const { loading, pagination, sizeChange, currentChange, tableData, handleDelete, search } =
  useTable(
    (pagin) =>
      getList({
        pageNo: pagin.pageNum,
        pageSize: pagin.pageSize,
        ...searchForm.value,
      }),
    { getCountStatistics }
  );
getCountStatistics();
async function getCountStatistics() {
  const params = {
    ...searchForm.value,
  };
  try {
    const res = await getCount(params);
    countMap.value = {
      total: 0,
      1: 0,
      2: 0,
      3: 0,
    };
    let totalCount = 0;
    res.data.forEach((item) => {
      countMap.value[item.classValue] = item.classCount;
      totalCount += Number(item.classCount);
    });
    countMap.value.total = totalCount;
  } catch (error) {
    console.log(error);
  }
}
//点击新增
const handleAdd = () => {
  editModalRef.value.add();
};
//点击编辑
const handleEdit = (id, isAuditor, taskId) => {
  editModalRef.value.edit(id, isAuditor, taskId);
};
//点击删除
const handleDel = (id) => {
  handleDelete(delRecords, id);
};
//批量删除
const handleDelSelect = () => {
  //获取当前选中行
  const selectRows = tableRef.value.getSelectionRows();
  if (!selectRows.length) {
    ElMessage({
      message: "请选择要删除的数据！",
      type: "warning",
    });
    return;
  }
  const ids = selectRows.map((item) => item.id);
  handleDelete(delRecords, ids.join(","));
};
//点击审核
const handleCheck = (id, processId) => {
  checkModalRef.value.check(id, processId);
};
//点击撤销
const handleCancel = (processId, cId) => {
  cancelId.value = cId;
  ElMessageBox.confirm("撤销后，该审批流程将自动结束，是否确认取消？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      cancelLoading.value = true;
      const res = await cancelProcess(processId);
      if (res.data) {
        ElMessage({
          message: "操作成功！",
          type: "success",
        });
        handleSearch();
      } else {
        ElMessage({
          message: "操作失败！",
          type: "error",
        });
      }
    } catch (error) {
      console.log(error);
    } finally {
      cancelLoading.value = false;
    }
  });
};
//点击预览详情
const handleView = (id) => {
  viewModalRef.value.view(id);
};
//获取导出字段
const getExportFileds = async () => {
  try {
    const params = {
      exportType: "ethical",
    };
    const res = await exportFields(params);
    if (res.code == 200) {
      res.data.forEach((item) => {
        exportFieldList.value.push({
          lable: item.showName,
          value: item.field,
          isSelect: true,
        });
      });
    }
  } catch (error) {
    console.log(error);
  }
};
//点击导出按钮
const handleExport = async () => {
  if (!exportFieldList.value.length) {
    await getExportFileds();
  }
  exportVisible.value = true;
};
//导出字段选择完毕
const handleSelectOk = async (val) => {
  const cols = val.map((item) => item.prop);
  try {
    const params = {
      ...searchForm.value,
      exportStr: cols.join(","),
    };
    const res = await exportRecords(params);
    if (res.type != "application/json") {
      downloadFile(res, exportTitle + ".xlsx");
    } else {
      ElMessage({
        message: "导出失败！",
        type: "error",
      });
    }
  } catch (error) {
    console.log(error);
  }
};
//执行检索并获取数量统计
const handleSearch = () => {
  search();
  getCountStatistics();
};
//点击重置
const resetForm = () => {
  searchFormRef.value.resetFields();
  searchForm.value.startTime = "";
  searchForm.value.endTime = "";
  handleSearch();
};
</script>

<style scoped lang="scss"></style>
